package com.mingliqiye.minecraft.enchantment.conflict.neoforge;

import static com.mingliqiye.minecraft.enchantment.conflict.common.NetWorkUtils.isLocalAddress;

import com.mingliqiye.minecraft.enchantment.conflict.common.ConfigManager;
import com.mingliqiye.minecraft.enchantment.conflict.common.MinecraftMod;
import com.mingliqiye.minecraft.enchantment.conflict.common.VersionsEnum;
import com.mingliqiye.minecraft.enchantment.conflict.common.WebConfigCore;
import com.mingliqiye.minecraft.enchantment.conflict.common.enchantment.EnchantmentController;
import com.mingliqiye.minecraft.enchantment.conflict.neoforge.network.ConfigPayload;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Mod(MinecraftMod.MOD_ID)
public class NeoForgeMod {

    public static final Logger LOGGER = LoggerFactory.getLogger(MinecraftMod.MOD_ID);
    public static MinecraftServer SERVER;

    public static final ConfigManager CONFIGMANAGER = new ConfigManager(
        FMLPaths.CONFIGDIR.get(),
        LOGGER,
        VersionsEnum.V121
    );

    public static final WebConfigCore WEBCONFIGCORE = new WebConfigCore(
        CONFIGMANAGER,
        new NeoForgeWebConfigCoreMeMethod()
    );

    public static final EnchantmentController ENCHANTMENTCONTROLLER = new EnchantmentController(CONFIGMANAGER);

    public NeoForgeMod(IEventBus modEventBus, ModContainer container) {
        modEventBus.addListener(this::commonSetup);
        modEventBus.register(ConfigPayload.class);
        NeoForge.EVENT_BUS.register(this);
    }

    private void commonSetup(final FMLCommonSetupEvent event) {}

    @SubscribeEvent
    public void onServerStarted(ServerStartedEvent event) {
        SERVER = event.getServer();
        WEBCONFIGCORE.start();
    }

    @SubscribeEvent
    public void onServerStopping(ServerStoppingEvent event) {
        WEBCONFIGCORE.stop();
    }

    @SubscribeEvent
    public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) {
        if (event.getEntity() instanceof ServerPlayer player) {
            ConfigPayload.sendConfig(player);
            LOGGER.debug("Sent config to player: {}", player.getName().getString());
        }
    }

    @SubscribeEvent
    public void onRegisterCommands(RegisterCommandsEvent event) {
        LOGGER.info("onRegisterCommands");
        event
            .getDispatcher()
            .register(
                Commands.literal("enchantmentdoesnotconflict-config").executes((context) -> {
                        var source = context.getSource();
                        boolean isLocal =
                            source.getServer().isSingleplayer() ||
                            source.getEntity() == null ||
                            (source.getPlayer() != null &&
                                isLocalAddress(source.getPlayer().connection.getRemoteAddress()));
                        if (isLocal) {
                            WEBCONFIGCORE.openWeb();
                            source.sendSuccess(
                                () ->
                                    Component.literal("打开")
                                        .append(Component.literal(WEBCONFIGCORE.getLocalUrl()))
                                        .withStyle(
                                            Style.EMPTY.withColor(ChatFormatting.BLUE).withUnderlined(true) // 蓝色带下划线
                                        )
                                        .append(Component.literal("成功"))
                                        .withStyle(ChatFormatting.GREEN),
                                true
                            );
                        } else {
                            source.sendFailure(
                                Component.literal("请使用服务器所在的机器执行该命令").withStyle(ChatFormatting.RED)
                            );
                        }
                        return 1;
                    })
            );
    }
}
